(** Boring system related stuff,
    like event handling and timers. *)

let keyHash = Hashtbl.create 256;;
let lastTime = ref 0;;
let deltaT = ref 0;;

(** Initialize everything! *)
let init () =
  Sdl.init [`EVERYTHING];
  lastTime := Sdltimer.get_ticks () ;
  Sdlvideo.set_video_mode 500 500 [`OPENGL];;


(** Handle system events and swap the backbuffer *)
let pump () = 
  Sdlevent.pump () ;
  Sdlgl.swap_buffers () ;
  let now = Sdltimer.get_ticks () in
    deltaT := now - !lastTime;
    lastTime := now;
    Hashtbl.iter 
      (fun k v ->
	 if Sdlkey.is_key_pressed k then
	   v k)
      keyHash ;;

(** Calls the given function when a key is pressed
    @param k The key; type Sdlkey.t
    @param f The function to call; type Sdlkey.t -> unit *)

let onKey k f = 
  Hashtbl.add keyHash k f;;
  
(** Remove a callback for a keypress
    @param k The key to ignore *)
let delKey k = 
  Hashtbl.remove keyHash k;;

(** The number of milliseconds since the last frame was rendered *)
let delta () =
  !deltaT ;;

(** Is the given key down? *) 
let keydown = Sdlkey.is_key_pressed ;;
